using System;
using System.Collections.Generic;
using System.Text;
using IAS.MacroRenderings.Interfaces;
using System.Data.SqlClient;
using System.Data;
using Microsoft.ApplicationBlocks.Data;
using System.Web;
namespace IAS.MacroRenderings.Data
{
    public class DataDB : DataBase, IDropDownListDataProvider
    {
        #region IDropDownListDataProvider Members

        private const string csvFolder = "/data/MacroRenderings/db/";
        private const string extension = ".config";
        //IsmailDbTest.config
        public Dictionary<string, string> GetData()
        {
            Dictionary<string, string> dt=null;
            
            string file = HttpContext.Current.Server.MapPath(csvFolder + className + extension);
            try
            {
                //this will give us constring and query;    
                Helper.DbConn db = Helper.Utility.GetDBDetails(file);

                using (SqlDataReader dr = SqlHelper.ExecuteReader(db.ConnString, CommandType.Text, db.Query))
                {
                    dt = convertToDictionary(dr);
                }
            }
            catch (Exception ex) {
                this.LogErrorToUmbraco(ex.Message.ToString() + "processing connection dbconn file " +  file);
            }
            return dt;         
        
        }

        /// <summary>
        /// convert the sql datareader to dictionary
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Dictionary<string, string> convertToDictionary(SqlDataReader dr)
        {
            Dictionary<string, string> dt = new Dictionary<string, string>();
            while (dr.Read()) {
                dt.Add(dr[0].ToString(), dr[1].ToString());                
            }
            return dt;
        }

        #endregion

        #region IDropDownListDataProvider Members

        /// <summary>
        /// in this case we assume the file we are reading has db connection entry mapping
        /// in web.config and the second item is a query to get you the values we will assume 
        /// 0 is the key and 1 is the value
        /// </summary>
        public string ClassName
        {
            set { this.className = value; }
        }

        #endregion
    }
}
